package com.feimt.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.feimt.common.BaceContent;
import com.feimt.common.R;
import com.feimt.pojo.ShoppingCart;
import com.feimt.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @PostMapping("add")
    public R add(@RequestBody ShoppingCart shoppingCart){
        log.info("shoppingCart:{}",shoppingCart);

        //1.获取个人信息
        Long auth = BaceContent.getThreadLocal();

        //2.获取个人购物车 有没有这个菜/套餐
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        qw.eq(ShoppingCart::getUserId,auth);
        qw.eq(!StringUtils.isEmpty(shoppingCart.getDishId()),ShoppingCart::getDishId,shoppingCart.getDishId());
        qw.eq(!StringUtils.isEmpty(shoppingCart.getSetmealId()),ShoppingCart::getSetmealId,shoppingCart.getSetmealId());

        ShoppingCart one = shoppingCartService.getOne(qw);

        if(one != null){
            //2.1 有==> 数量加1 update
            Integer o_number = one.getNumber();
            one.setNumber(o_number + 1);
            shoppingCartService.updateById(one);
            return R.success(one);
        }else {
            //2.2 没==> save  默认1
            shoppingCart.setUserId(auth);
            shoppingCart.setNumber(1);
            shoppingCartService.save(shoppingCart);
            return R.success(shoppingCart);
        }

    }

    /**
     * 查看购物车
     * @return
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> list(){
        log.info("查看购物车...");

        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,BaceContent.getThreadLocal());
        queryWrapper.orderByAsc(ShoppingCart::getCreateTime);

        List<ShoppingCart> list = shoppingCartService.list(queryWrapper);

        return R.success(list);
    }
}

